import importlib, pvporcupine._util as pv_util
pv_util._LINUX_CPU_PART_MAP['0xd04'] = 'cortex-a53'   # 热补丁
importlib.reload(pv_util)     # 刷新模块
import pvporcupine            # 现在正常导入

import pyaudio
import struct
from pydub import AudioSegment
from pydub.playback import play


# Picovoice 配置
ACCESS_KEY = "eDcXuRvPczyj/LovUQJB1wZdBM0zmG3L7aHMpP1O2Ntb0S4VI8OMgQ=="  # 替换为你的 Picovoice Access Key
KEYWORD_PATHS = [
    "./zx.ppn",  # 替换为你的名字模型路径
    "./zx.ppn"  # 替换为你的昵称模型路径
]

class WakeWordDetector:
    def __init__(self):
        # 初始化 Porcupine
        self.porcupine = pvporcupine.create(
            access_key=ACCESS_KEY,
            keyword_paths=KEYWORD_PATHS,
            sensitivities=[0.5, 0.5]  # 灵敏度 (0-1)
        )
        
        # 初始化音频流
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(
            rate=self.porcupine.sample_rate,
            channels=1,
            format=pyaudio.paInt16,
            input=True,
            frames_per_buffer=self.porcupine.frame_length,
            input_device_index=None  # 使用默认麦克风
        )
        
        print(f"监听唤醒词: {self.get_keyword_names()}")
        print("等待唤醒... (按 Ctrl+C 退出)")

    def get_keyword_names(self):
        """获取唤醒词名称列表"""
        return [path.split('/')[-1].replace('.ppn', '') for path in KEYWORD_PATHS]

    def play_response(self):
        """播放响应音频"""
        try:
            sound = AudioSegment.from_wav("imhere.WAV")
            play(sound)
            print("我在")
        except Exception as e:
            print(f"播放音频失败: {e}")

    def run(self):
        try:
            while True:
                # 读取音频帧
                pcm = self.stream.read(self.porcupine.frame_length)
                pcm = struct.unpack_from("h" * self.porcupine.frame_length, pcm)
                
                # 检测唤醒词
                result = self.porcupine.process(pcm)
                if result >= 0:  # 检测到唤醒词
                    keyword = self.get_keyword_names()[result]
                    print(f"检测到唤醒词: {keyword}")
                    self.play_response()
                    
        except KeyboardInterrupt:
            print("正在停止...")
        finally:
            # 清理资源
            self.stream.close()
            self.audio.terminate()
            self.porcupine.delete()

if __name__ == "__main__":
    detector = WakeWordDetector()
    detector.run()

